module BlogEntriesHelper
  include PhotosHelper
  
  def tags_of blog_entry
    html = ""
    blog_entry.tags.each do |tag|
      html += link_to(tag.name, tagged_blog_url(:tag => tag.name))
      html += "&nbsp;&nbsp;"
    end
    html
  end
  
  def blog_body blog_entry
    replace_photo_references blog_entry
    replace_music_references blog_entry
    replace_lyrics_activatable blog_entry
    replace_html_newlines blog_entry
    replace_newlines blog_entry
    blog_entry.body.untaint
  end
    
  def replace_newlines blog_entry
    blog_entry.body.gsub!("\n","<br/>")
  end
  
  def replace_photo_references blog_entry
    body = blog_entry.body
    body.clone.scan(/\[{2}P(\d+)\]{2}/) { |match|
      body.gsub!("[[P#{match.to_s}]]",
        %Q( <div class="photo-embed"> #{display_photo(
                                    Photo.find(match.to_s),
                                    false,
                                    blog_entry)} </div> ) )
    }
    body.clone.scan(/\[{2}PT(\d+)\]{2}/) { |match|
      body.gsub!("[[PT#{match.to_s}]]",
        %Q( #{display_photo(
                Photo.find(match.to_s),
                true,
                blog_entry)} ) )
    }
  end

  def replace_lyrics_activatable blog_entry
    blog_entry.body.gsub!(
      "[[L]]",
      %Q(<span class="lyrics-activate">#{link_to_function("Lyrics", "Lyrics.activate(this)")}</span>))
  end
  
IMEEM_CODE = 
  %Q(<div style="text-align: center;"><object width="400" height="80"><param name="movie" value="http://media.imeem.com/m/IMEEMID/aus=false/"></param><param name="wmode" value="transparent"></param><param name="FlashVars" value="backColor=FFFFFF&primaryColor=FFFFFF&secondaryColor=FFFFFF&linkColor=CCAA00"></param><embed src="http://media.imeem.com/m/IMEEMID/aus=false/" type="application/x-shockwave-flash" width="400" height="80" wmode="transparent"FlashVars="backColor=FFFFFF&primaryColor=FFFFFF&secondaryColor=FFFFFF&linkColor=CCAA00"></embed></object></div>)
  
  def replace_music_references blog_entry
    body = blog_entry.body
    if body =~ /\[{2}M-(\S+)\]{2}/
      body.gsub!(/\[{2}M-\S+\]{2}/, 
        IMEEM_CODE.gsub("IMEEMID", $1))
    end
    body
  end
  
  def replace_html_newlines blog_entry
    body = blog_entry.body
    body.gsub!(/<table.*>.*?<\/table>/m) {|m| m.tr("\n",'') }
    body.gsub!(/<ul.*>.*?<\/ul>/m) {|m| m.tr("\n",'') }
  end
  
end
